package proeva;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;

public class DDoS_H_Servlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public DDoS_H_Servlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		//返回的json形式数据
		String json;
		
		
		//解析request中的参数
		//?cmd=calc  求绩效值
		if( request.getParameter("cmd").equalsIgnoreCase("calc"))
		{
			//完成绩效的计算
			//参数形式：
			//UDP---?UorS=u&bitrate=100&requestrate=10&requestsize=100&filesize=5000000&hitratio=1.1&averestime=1.2
			//SYN---?UorS=s&bitrate=100&qlimit=20&requestrate=10&requestsize=100&filesize=5000000&hitratio=1.1&averestime=1.2
			DDoS_H test = new DDoS_H();

			double bitrate = Double.parseDouble( request.getParameter("bitrate") );
			double requestrate = Double.parseDouble( request.getParameter("requestrate") );
			double requestsize = Double.parseDouble( request.getParameter("requestsize") );
			double filesize = Double.parseDouble( request.getParameter("filesize") );
			int qlimit = 0;
			double hitratio_real = Double.parseDouble( request.getParameter("hitratio") );
			double averestime_real = Double.parseDouble( request.getParameter("averestime") );

			test.setBitrate( bitrate );
			test.setRequestRate( requestrate );
			test.setRequestSize( requestsize );
			test.setFileSize( filesize );
			test.setHitRatio_Real(hitratio_real);
			test.setAveResTime_Real(averestime_real);

			if( request.getParameter("UorS").equalsIgnoreCase("u") )//UDP
			{
				test.CalcEva_udp();
			}
			else//SYN
			{
				qlimit = Integer.parseInt( request.getParameter("qlimit") );
				test.setQlimit( qlimit );
				test.CalcEva_SYN();
			}
			//生成json返回
			json = "{success:true,msg:‘成功计算出绩效值’,data:{eva:" + test.getEva() + "}}";
			out.write(json);
		}
		//?cmd=show  列出历史数据
		//完成历史数据查询
		//传入UorS
		else if( request.getParameter("cmd").equalsIgnoreCase("show") )
		{
			if( request.getParameter("UorS").equalsIgnoreCase("u") )//udp
			{
				try
				{
					Connection Conn = DBSetting.GetEvaConnection();
					Statement stmt = Conn.createStatement();
					ResultSet result = stmt.executeQuery("SELECT * FROM DDoS_Eva_H WHERE Type='true' ORDER BY Eva_Time DESC");
					StringBuffer data = new StringBuffer("");
					while( result.next() )
					{
						data.append("{Eva_Time:");
						data.append(result.getTimestamp("Eva_Time"));

						data.append(",Bitrate:");
						data.append(result.getDouble("Bitrate"));

						data.append(",RequestRate:");
						data.append(result.getDouble("RequestRate"));

						data.append(",RequestSize:");
						data.append(result.getDouble("RequestSize"));

						data.append(",FileSize:");
						data.append(result.getDouble("FileSize"));

						data.append(",Eva:");
						data.append(result.getDouble("Eva"));

						data.append("},");
					}
					if( data.length() != 0)
						data.deleteCharAt(data.length() - 1);
					json = "{success:true,msg:'查询数据库成功',data:{"+ data +"}}";
					out.write(json);
					
					result.close();
					stmt.close();
					Conn.close();
				}
				catch( Exception ex )
				{
					json = "{success:false,msg:'查询数据库时出错，请重试',data:{}}";
					out.write(json);
//					out.write(ex.getMessage());
					return;
				}
			}
			else if( request.getParameter("UorS").equalsIgnoreCase("s") )//SYN
			{
				try
				{
					Connection Conn = DBSetting.GetEvaConnection();
					Statement stmt = Conn.createStatement();
					ResultSet result = stmt.executeQuery("SELECT * FROM DDoS_Eva_H WHERE Type='false' ORDER BY Eva_Time DESC");
					StringBuffer data = new StringBuffer("");
					while( result.next() )
					{
						data.append("{Eva_Time:");
						data.append(result.getTimestamp("Eva_Time"));

						data.append(",Bitrate:");
						data.append(result.getDouble("Bitrate"));

						data.append(",RequestRate:");
						data.append(result.getDouble("RequestRate"));

						data.append(",RequestSize:");
						data.append(result.getDouble("RequestSize"));
						
						data.append(",Qlimit:");
						data.append(result.getInt("Qlimit"));

						data.append(",FileSize:");
						data.append(result.getDouble("FileSize"));

						data.append(",Eva:");
						data.append(result.getDouble("Eva"));

						data.append("},");
					}
					if( data.length() != 0 )
						data.deleteCharAt(data.length() - 1);
					json = "{success:true,msg:'查询数据库成功',data:{"+ data +"}}";
					out.write(json);
					
					result.close();
					stmt.close();
					Conn.close();
				}
				catch( Exception ex )
				{
					json = "{success:false,msg:'查询数据库时出错，请重试',data:{}}";
					out.write(json);
					out.write(ex.getMessage());
					return;
				}
			}
			else
			{
				json = "{success:false,msg:'传入参数有误，请重试',data:{}}";
				out.write(json);
				return;
			}
		}
		//cmd=save
		//保存到数据库
		//传入格式：
		//cmd=save?UorS=u&bitrate=100&requestrate=10&requestsize=100&filesize=5000000&hitratio=1.1&averestime=1.2&eva=1212
		//cmd=save?UorS=s&bitrate=100&requestrate=10&requestsize=100&filesize=5000000&qlimit=10&hitratio=1.1&averestime=1.2&eva=121
		else if( request.getParameter("cmd").equalsIgnoreCase("save") )
		{
			double bitrate = Double.parseDouble( request.getParameter("bitrate") );
			double requestrate = Double.parseDouble( request.getParameter("requestrate") );
			double requestsize = Double.parseDouble( request.getParameter("requestsize") );
			double filesize = Double.parseDouble( request.getParameter("filesize") );
			int qlimit = 0;
			double hitratio_real = Double.parseDouble( request.getParameter("hitratio") );
			double averestime_real = Double.parseDouble( request.getParameter("averestime") );
			
			boolean isUDP = true;
			if( !request.getParameter("UorS").equalsIgnoreCase("s") )//SYN
			{
				isUDP = false;
				qlimit = Integer.parseInt( request.getParameter("qlimit") );
			}
			
			double Eva = Double.parseDouble( request.getParameter("eva") );
			//保存到数据库
			try
			{
				Connection Conn = DBSetting.GetEvaConnection();
				PreparedStatement pstmt = Conn.prepareStatement("INSERT INTO DDoS_Eva_H(Type, Eva_Time, Bitrate, RequestRate, RequestSize, Qlimit, FileSize, HitRatio_Real, AveResTime_Real, Eva) VALUES (?,?,?,?,?,?,?,?,?,?)");
				pstmt.setBoolean(1, isUDP);
				pstmt.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
				pstmt.setDouble(3, bitrate);
				pstmt.setDouble(4, requestrate);
				pstmt.setDouble(5, requestsize);
				pstmt.setInt(6, qlimit);
				pstmt.setDouble(7, filesize);
				pstmt.setDouble(8, hitratio_real);
				pstmt.setDouble(9, averestime_real);
				pstmt.setDouble(10, Eva);
				pstmt.execute();
				
				json = "{success:true,msg:'成功将结果保存到数据库',data:{}}";
				out.write(json);

				pstmt.close();
				Conn.close();
			}
			catch( Exception ex )
			{
				json = "{success:false,msg:'将计算结果保存到数据库时出错，请重试',data:{}}";
				out.write(json);
				out.write(ex.getMessage());
				return;
			}
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet( request, response);
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
